package com.example.new9.presenter;

import android.app.Activity;
import android.content.Context;
import android.util.Log;


import com.example.new9.contact.WeatherContact;
import com.example.new9.entity.Weather;
import com.example.new9.service.WeatherService;

import java.util.Objects;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class WeatherPresenter implements WeatherContact.WeatherPresenter {
    private WeatherContact.WeatherView view ;
    private Context context ;
    private Activity activity ;
    public WeatherPresenter(WeatherContact.WeatherView view , Context context , Activity activity){
        this.view = view ;
        this.context = context ;
        this.activity = activity ;
    }
    @Override
    public void getData(String city) {
        String url = "http://apis.juhe.cn/" ;
        String key = "251518e073ef6c3c9504dd286c3f6a86" ;

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build() ;
        WeatherService service = retrofit.create(WeatherService.class) ;
        service.getData(city , key)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Weather>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Weather weather) {
                        if (view != null){
                            view.showData(weather);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("数据错误", Objects.requireNonNull(e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
